package com.umpay.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.umpay.exception.BusinessException;

/**
 * 
 * <p>
 * Title:SequenceUtil
 * </p>
 * <p>
 * Description: 获取序列的工具类 可根据需要继续扩充
 * </p>
 * <p>
 * Company: UMPAY
 * </p>
 * 
 * @author lifeng
 * @date 2018年1月17日
 */
@Component
public class SequenceUtil {
	private static Map<String, SeqZone> seqMap = new HashMap<String, SeqZone>();

	private static final Integer EVERY_TIME_AMOUNT = 20;

//	@Autowired
//	private SequenceDao seqDao;

	/**
	 * @param key
	 * @param width
	 * @return 返回width-1位序列+库标识
	 * @throws BusinessException
	 */
	public synchronized String getSeq(String key, int width) {
		SeqZone zone = seqMap.get(key);
		if (seqMap.get(key) == null || zone.isUsedUp()) {
			HashMap<String, Object> param = new HashMap<String, Object>();
			param.put("in_seqid", key);
			param.put("in_interval", EVERY_TIME_AMOUNT);
//			seqDao.getBatchSeq(param);
			zone = new SeqZone((Integer) param.get("out_seq_begin"), (Integer) param.get("out_seq_end"));
			seqMap.put(key, zone);
		}
		return formatSequence(String.valueOf(zone.next()), width);
	}

	/**
	 * 
	 * description: 将传入的字符串的长度限制为一定值
	 * 
	 * @param is
	 * @param width
	 * @return
	 */
	private static String formatSequence(String is, int width) {
		if (is.length() < width)
			for (; is.length() < width; is = "0" + is)
				;
		else
			is = is.substring(is.length() - width, is.length());
		return is;
	}

	private static class SeqZone {
		private AtomicInteger low;

		private int high;

		public SeqZone(int low, int high) {
			this.low = new AtomicInteger(low);
			this.high = high;
		}

		public int next() {
			return low.incrementAndGet();
		}

		public boolean isUsedUp() {
			return low.intValue() >= high;
		}

	}
}
